const fs = require('fs')
const path = require('path')
const readline = require('readline');
const logger = require('../../util/logger')

const {
  root,
  target,
} = require('../config')
const createFoldersAndFiles = require('../script/createFoldersAndFiles')
const getFilesStartingWith = require('../../util/getFilesStartingWith')
const copyAndRenameFiles = require('../script/copyAndRenameFiles')

function getModuleObj(filePath) {
  let start, end, flag = false, i = 0
  return new Promise((resolve, reject) => {
    const rl = readline.createInterface({
      input: fs.createReadStream(filePath),
      output: process.stdout,
      terminal: false
    });

    rl.on('line', (line) => {
      if (!flag && line.trim().indexOf('atlas: Object.values(Object.assign') === 0) {
        start = i - 1
        flag = true
      }
      if (flag && line.trim().indexOf('=') <= 4 && line.trim().indexOf('=') > 0) {
        end = i
        resolve({
          start,
          end,
        })
      }
      i++
    });

    rl.on('close', () => {
      resolve(false);
    });
  });
}

function readLinesInRange(filePath, startLine, endLine) {
  return new Promise((resolve, reject) => {
    const rl = readline.createInterface({
      input: fs.createReadStream(filePath),
      output: process.stdout,
      terminal: false
    });

    let lines = [];
    let currentLine = 0;

    rl.on('line', (line) => {
      currentLine++;
      if (currentLine >= startLine && currentLine <= endLine) {
        lines.push(line);
      }
      if (currentLine > endLine) {
        rl.close();
      }
    });

    rl.on('close', () => {
      resolve(lines);
    });
  });
}

async function getModuleGenV0() {
  const filePath = path.join(root, getFilesStartingWith(root, 'vendors').pop())
  const imagesRoot = path.join(root, 'images')
  const moduleObjPosition = await getModuleObj(filePath)
  const modules = []
  const errList = []

  const objStr = await readLinesInRange(filePath, moduleObjPosition.start, moduleObjPosition.end)
  const obj = eval((objStr.join('\n')).slice(0, -1) + ';')

  const allModule = Object.keys(obj)

  for (const name of allModule) {
    const skeletonData = obj[name].json
    const atlasData = obj[name].atlas

    const fileName = name
    const skeletonText = JSON.stringify(skeletonData)
    const atlasText = atlasData

    try {
      createFoldersAndFiles(target, fileName, skeletonText, atlasText)
      modules.push(fileName)
      console.log(`${fileName} 拆解完成`)
    } catch (e) {
      errList.push(fileName)
      console.log(`${fileName} 拆解失败`)
    }
  }

  if (modules.length) {
    logger.info(`模型总数：${modules.length}\n模型列表：\n${modules.join('\n')} \n\n`)
    console.log('拆解模型列表……')
    console.log(modules)

    /* 第四步：复制模型图片 */
    console.log('第四步：复制模型图片……')
    logger.info('第四步：复制模型图片……')
    copyAndRenameFiles(imagesRoot, target, modules)

    if (errList.length) {
      console.log('部分模型拆解失败')
      logger.error('部分模型拆解失败')
      logger.error(`拆解失败模型：\n${errList.join('\n')}\n\n`)
    }

    return true
  } else {
    if (errList && errList.length) {
      console.log('拆解模型列表失败')
      logger.error('拆解模型列表失败')
      return false
    } else {
      console.log('未识别到模型，请手工操作')
      logger.error('未识别到模型，请手工操作')
      return false
    }
  }
}

module.exports = getModuleGenV0
